<template>
  <div id="Search" :style="thisStyle()">
    <!--搜索框-->
    <div class="searchClass" :style="searchStyle()" aria-readonly="true">
      <!--todo  el-autocomplete 带推荐搜索输入建议-->
      <input ref="searchInput" :placeholder="searchInputTip" v-model="inputValue" @keyup.enter="searchClick"
             @focusin="searchInputIn" @focusout="searchInputOut" :title="inputValue" :style="searchInputStyle"/>
      <i class="el-icon-close clearIcon" @click="searchInputClear" v-show="inputValue" title="清空"></i>
      <el-button type="success" icon="el-icon-search" title="搜索" class="searchButton" @click="searchClick"
                 @dblclick.native="goOutSearch(inputValue)" style="margin-left: -43px;"></el-button>
    </div>
    <!--搜索提示-->
    <p v-loading="searchLoading"></p>
    <p class="searchTip" ref="searchTip" hidden>
      共找到相关结果<span style="color: lightcyan">&thinsp;
      {{ (pageTotal || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') }}</span>&thinsp;条
    </p>
    <p ref="searchResultEmpty" hidden @click="searchInputClear">
      <el-empty description=" " style="cursor: grab;color: azure">
        <el-tooltip placement="bottom-start" effect="light">
          <span slot="content" style="color: cornflowerblue"> >^< 试试站外搜索 </span>
          <span @click="outSearch(inputValue,7)" style="cursor: pointer;">这是一个空盒子.</span>
        </el-tooltip>
      </el-empty>
    </p>
    <!--搜索结果页 searchResultHeight-->
    <div class="searchResult" :style="searchResultHeight()">
      <div v-for="item in searchResultData" class="searchResultItem">
        <div>
          <p class="itemTitle" @click="detail(item.href,item.type,item.subtype,item.id,item.from)">{{ item.title }}</p>
          <p class="itemBlurb" @click="detail(item.href,item.type,item.subtype,item.id,item.from)" title="点击查看">
            {{ item.blurb }}</p>
          <p style="font-size: 13px;color: #444;">
            <!--<a :href="localPath + item.href" target="_blank" style="cursor:pointer;">{{ localPath + item.href }}</a>-->
            <el-tooltip content="模块标签" placement="bottom-start" effect="light">
              <span style="cursor:pointer;"> &ensp;
                <a :href="localPath + item.href" target="_blank">
                  <i class="el-icon-collection-tag" title="">&ensp;</i>{{ item.moduleName }}
                </a>
              </span>
            </el-tooltip>
            <span style="font-size: 13px;">&ensp;
              <i class="el-icon-time" title="时间">&ensp;{{ item.createTime }}</i>&emsp;
              <i class="el-icon-star-off" title="星星">&ensp;{{ item.starNum }}</i>&emsp;
              <i class="el-icon-edit" title="作者" v-show="item.author">&ensp;{{ item.author }}</i>&emsp;
              <i class="el-icon-position" title="来源" v-show="item.from">
                 &ensp;{{ item.from.length > 40 ? item.from.substring(0, 39) + ".." : item.from }}
              </i>
            </span>
          </p>
        </div>
        <div v-if="item.images"><img :src="item.images" alt=" " title=""></div>
      </div>
    </div>
    <!--搜索结果页页脚-->
    <div class="pageLimit" ref="pageLimit" hidden>
      <el-button type="primary" icon="el-icon-d-arrow-left" @click="lastNumPage(5)" title="上五页"
                 @contextmenu.prevent.stop.native="lastNumPage(0)"></el-button>
      <el-button type="primary" icon="el-icon-arrow-left" @click="lastPage" title="上一页"></el-button>
      <el-button type="primary" v-for="i in pageNums" :key="i" @click="numPage(i+1)" :style="numPageStyle(i+1)">
        {{ i + 1 }}
      </el-button>
      <el-button type="primary" icon="el-icon-arrow-right" @click="nextPage" title="下一页"></el-button>
      <el-button type="primary" icon="el-icon-d-arrow-right" @click="nextNumPage(5)" title="下五页"
                 @contextmenu.prevent.stop.native="nextNumPage(0)"></el-button>
    </div>
    <!--跳转弹窗-->
    <el-dialog title="提示" :visible.sync=outSearchDialogShow :modal='false' width="20%" height="5%" center
               @close='outSearch(inputValue,-1)' style="margin-top:7%">
      <span style="font-size:17px;">.<el-icon class="el-icon-position"/>前往站外搜索>>>{{ outSearchTime }}秒后.</span>
      <span slot="footer" class="dialog-footer">
          <el-button @click="outSearch(inputValue,-1)" type="info">取 消</el-button>
          <el-button @click="outSearch(inputValue,0)" type="primary">立即前往</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import webSearch from '../../apis/WebSearch'

export default {
  name: 'Search',

  data() {
    return {
      localPath: window.location.protocol + "//" + window.location.hostname + ":" + window.location.port + "/#/",
      windowWidth: document.documentElement.clientWidth,  //实时屏幕宽度
      windowHeight: document.documentElement.clientHeight,   //实时屏幕高度w
      //searchStyle: 'margin-top: 17%;',
      searchInputTip: '站内搜索',
      inputValue: '',
      searchResultData: [],
      pageTotal: 0,
      pageNums: [], //页数组
      pageNum: 1, //初始页
      pageSize: 10, //    每页的数据
      searchLoading: false,
      searchInputStyle: "",
      outSearchDialogShow: false,
      outSearchTime: 7,
    }
  },
  created() {
  },
  mounted() {
    // 页面渲染完成时自动聚焦到搜索输入框，ref="searchInput"
    if (window.location.port && window.location.port !== 80) {
      this.$nextTick(() => {
        setTimeout(() => this.$refs.searchInput.focus(), 7000);
      })
    }
  },
  methods: {
    thisStyle() {
      if (this.searchResultData.length) {
        return "width: 120%; margin-left: -10%;"
      } else {
        return "width: 50%; margin-left: 25%;"
      }
    },
    searchStyle() {
      if (this.searchResultData.length) {
        return "width:42%;margin-left:29%;"
      } else {
        return "margin-top: 17%;"
      }
    },
    searchInputClear() {
      this.inputValue = '';
      this.$refs.searchInput.focus();
      if (!this.searchResultData.length) {
        this.$emit("searchState", "");//自定义事件  传递值“子向父组件传值”
        this.$refs.searchTip.hidden = true
        this.$refs.searchResultEmpty.hidden = true
      }
    },
    searchInputIn() {
      this.searchInputTip = '';
      this.searchInputStyle = "background: #496999;width:52%;"
    },
    searchInputOut() {
      this.searchInputTip = '站内搜索';
      if (this.inputValue) {
        this.searchInputStyle = "background: #496999;width:52%;"
      } else {
        this.searchInputStyle = "background: #497999;"
        if (this.searchResultData.length) {
          this.searchInputStyle = "width:52%;"
        }
      }
    },
    searchClick() {
      this.pageNum = 1;
      this.search();
    },
    search() {
      if (this.inputValue === '') {
        this.$emit("searchState", "");
        this.searchInputTip = '请输入关键词';
        this.$refs.searchTip.hidden = true
        this.searchResultData = [];
        this.searchInputStyle = ""
        this.$refs.searchResultEmpty.hidden = true
        this.$refs.pageLimit.hidden = true
        //this.searchStyle = 'margin-top: 17%;';
        console.log("搜素内容：" + this.inputValue);
        return;
      }
      this.$emit("searchState", "searched");
      this.searchLoading = true;
      let data = {};
      data.keyword = this.inputValue
      data.pageNum = this.pageNum
      data.pageSize = this.pageSize
      //console.log(data);
      webSearch.search(data)
        .then((res) => {
          //console.log(res);
          //console.log(res.data.records);
          this.searchLoading = false;
          this.$refs.searchTip.hidden = false
          if (res.status === 200) {
            this.pageTotal = res.data.total;
            this.searchResultData = res.data.records;
            if (this.searchResultData.length > 0) {
              // this.searchStyle = 'width:50%;margin-left:25%;';
              this.$refs.searchResultEmpty.hidden = true
              if (this.pageTotal > this.pageSize) {
                this.$refs.pageLimit.hidden = false;
                this.pageNums = this.pageNumsCount(this.pageTotal);
              } else {
                this.$refs.pageLimit.hidden = true;
              }
            } else {
              // this.searchStyle = 'margin-top: 17%;';
              this.$refs.searchResultEmpty.hidden = false
              this.$refs.pageLimit.hidden = true;
            }
          } else {
            this.$refs.searchTip.innerText = ">_< 搜素失败！请稍后再试..."
            console.log(res);
          }
        })
    },
    detail(href, type, subtype, id, from) {
      if (type === "热点") {
        from = from ? from : "/#/" + href
        window.open(from, '_blank')
        return;
      }
      if (id) {
        href = href + "/detail"
      }
      let routeData = this.$router.resolve({name: href, query: {type: type, subtype: subtype, id: id,}});
      console.log(JSON.stringify(routeData), href, type, subtype, id, from);
      window.open(routeData.href, '_blank')
    },
    ////分页数组计算函数--length要为偶数
    pageNumsCount(pageTotal, length) {
      length = length === undefined ? 10 : length;
      //总页数为总条数除页量有余进一
      let pageNums = [...new Array(Math.ceil(pageTotal / this.pageSize)).keys()]
      //总页数大于length当前页大于length/2开始截取总页数显示为当前页 - length/2 -1（下标多减1）到当前页+ length/2
      if (pageNums.length > length && this.pageNum > length / 2) {
        //splice(start,count) 函数是 从 start 下标开始截取共 count 个数
        pageNums = pageNums.splice(this.pageNum - length / 2, length);
      } else {
        pageNums = pageNums.splice(0, length)
      }
      return pageNums;
    },
    numPage(num) {
      this.pageNum = num
      this.search();
    },
    numPageStyle(i) {
      if (i === this.pageNum) {
        return "background: skyblue;"
      }
    },
    lastPage() {
      if (--this.pageNum < 1) {
        this.pageNum = 1
        return;
      }
      this.search();
    },
    nextPage() {
      if (++this.pageNum > this.pageNums.length) {
        this.pageNum = this.pageNums.length
        return;
      }
      this.search();
    },
    lastNumPage(num) {
      if (this.pageNum === 1) {
        return;
      }
      if (num === 0) {
        this.pageNum = 1
        this.search();
        return;
      }
      if (this.pageNum - num < 1) {
        this.pageNum = 1
      } else {
        this.pageNum = this.pageNum - num
      }
      this.search();
    },
    nextNumPage(num) {
      let totalPageNum = Math.ceil(this.pageTotal / this.pageSize)
      if (this.pageNum === totalPageNum) {
        return;
      }
      if (num === 0) {
        this.pageNum = totalPageNum
        this.search();
        return;
      }
      if (this.pageNum + num > totalPageNum) {
        this.pageNum = totalPageNum
      } else {
        this.pageNum = this.pageNum + num
      }
      this.search();
    },
    searchResultHeight() {
      return "height:" + (document.documentElement.clientHeight * 0.98 - 240) + "px;";
    },
    goOutSearch(keyword) {
      this.$confirm("是否站外搜素？", "提示", {
        iconClass: "el-icon-position green",
        showClose: true,
        type: "info",
      }).then(() => {
        this.outSearch(keyword, 0)
      }).catch((err) => {
        this.$notify.info('取消站外搜素')
      });
    },
    outSearch(keyword, time) {
      if (!keyword) {
        if (this.inputValue) {
          keyword = this.inputValue
        } else {
          console.log("!..! 搜索词" + this.inputValue)
        }
      }
      if (time < 0) {
        //取消跳转
        clearInterval(this.interval);
        this.outSearchDialogShow = false;
      } else if (time === 0) {
        //立刻跳转
        window.open("https://www.baidu.com/s?wd=" + keyword, '_blank');
        window.open("https://cn.bing.com/search?q=" + keyword, '_blank');
        this.outSearchDialogShow = false;
        clearInterval(this.interval);
      } else {
        //继续定时跳转 //time：延迟跳转的时间超过 4 秒 浏览器会拦截
        this.outSearchDialogShow = true;
        clearInterval(this.interval);
        this.interval = setInterval(() => {
          this.outSearchTime = time--;
          if (time === 0) {
            clearInterval(this.interval);
            this.outSearchDialogShow = false;
            window.open("https://www.baidu.com/s?wd=" + keyword, '_blank');
            window.open("https://cn.bing.com/search?q=" + keyword, '_blank');
          }
        }, 1000);
      }
    },

  }
}
</script>

<style>
#Search {
  color: white;
  text-align: center;
  position: absolute;
  margin-top: 1%;
}

.searchClass {

}

.searchClass input {
  width: 42%;
  height: 34px;
  border-radius: 4px;
  border: 2px solid teal;
  outline: none;
  background: #497999;
  font-size: 16px;
  font-weight: lighter;
  color: white;
  text-align: center;
}

.searchClass .el-button {
  background: mediumseagreen;
}

.searchClass .el-button:hover {
  background: lightgreen;
}

.searchClass input::placeholder {
  color: lightblue;
  font-size: 14px;
  text-align: center;
}

.clearIcon {
  position: absolute;
  margin-left: -78px;
  margin-top: 2px;
  padding: 8px;
  font-size: 19px;
  font-weight: bold;
  color: darkgrey;
  cursor: grab;
  background: #496999;
}

.clearIcon:hover {
  color: lightcyan;
  /*background: #497999;*/
}

.searchButton {
  width: 38px;
  height: 38px;
}

.searchTip {
  font-size: 13px;
  color: lightblue;
}

.searchResult {
  width: 56%;
  height: 80%;
  margin-left: 22%;
  margin-top: 0.5%;
  text-align: left;
  overflow: auto;

}

.searchResultItem {
  background: aliceblue;
  color: dimgrey;
  display: flex;
  border-bottom: 2px ridge steelblue;
}

.itemTitle {
  font-size: 16px;
  color: mediumblue;
  cursor: pointer;
}

.itemTitle:hover {
  color: dodgerblue;
  text-decoration: underline;
}

.itemBlurb {
  font-size: 14.5px;
  color: #333;
  cursor: pointer;
}

.itemBlurb:hover {
  color: #666;
}

.searchResultItem p {
  margin-left: 40px;
  margin-right: 40px;
}

.searchResultItem a {
  color: darkcyan;
}

.searchResultItem a:hover {
  color: darkgreen;
  text-decoration: underline;
}

.searchResultItem img {
  width: 100px;
  height: 95px;
  margin-top: 40px;
  margin-right: 20px;

}

.pageLimit {
  margin-top: 10px;
  text-align: center;
}

.pageLimit button {
  background: lightslategrey;
  width: 33px;
  height: 30px;
}


/*点击按钮样式 会从RightMenu中渲染*/

</style>
